/*
 *  Copyright (C) 2010 Zubanov Dmitry
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


/**
 *
 * @author Zubanov Dmitry aka javadimon, zubanov@gmail.com
 * Omsk, Russia, created 29.05.2010
 * (C) Copyright by Zubanov Dmitry
 */

package org.jssdb.core.handler;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jssdb.core.Serializabler;
import org.jssdb.core.utils.FileInfo;

/**
 *
 * @author Zubanov Dmitry aka javadimon, zubanov@gmail.com
 * Omsk, Russia,
 * created 08.05.2010
 */
public class SerializableHandler implements Serializabler{

   private static SerializableHandler self = null;
   static final Logger logger = Logger.getLogger(SerializableHandler.class.getName());

    private SerializableHandler(){
    }

    public static SerializableHandler getDefault(){
        if(self == null)
            self = new SerializableHandler();

        return self;
    }

    @Override
    public long serialaizable(FileInfo fInfo, Object obj) {
        if(fInfo == null || obj == null){
            return -1;
        }
        
        FileOutputStream fos = null;
        ObjectOutputStream out = null;
        try {
            fos = new FileOutputStream(fInfo.getFileName());
            OutputStream buffer = new BufferedOutputStream(fos, 8196);
            out = new ObjectOutputStream(buffer);
            out.writeObject(obj);
            out.close();
        } catch (IOException ex) {
            logger.log(Level.SEVERE, fInfo.toString(), ex);
        }

        return fInfo.getNumber();
    }

    public boolean serialaizable(String fileName, Object obj) {
        boolean result = false;
        FileOutputStream fos = null;
        ObjectOutputStream out = null;
        try {
            fos = new FileOutputStream(fileName);
            out = new ObjectOutputStream(fos);
            out.writeObject(obj);
            out.close();
            result = true;

        } catch (IOException ex) {
            logger.log(Level.SEVERE, fileName, ex);
            
        } finally{
            return result;
        }
    }

}
